package cn.iclass.modules.sys.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.iclass.common.constant.RedisKeys;
import cn.iclass.common.exception.GlobalException;
import cn.iclass.modules.sys.service.RedisService;
import cn.iclass.modules.sys.service.SysCaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @Description: 验证码
 * @Author: alan
 * @Date: 2019/6/10 5:24 PM
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl implements SysCaptchaService {
	@Resource
	private RedisService redisService;

	@Override
	public ICaptcha getCaptcha(String uuid) {
		if (StringUtils.isBlank(uuid)) {
			throw new GlobalException("uuid不能为空");
		}
		LineCaptcha captcha = CaptchaUtil.createLineCaptcha(130, 40, 4, 1);
		captcha.setGenerator(new RandomGenerator("1234567890", 4));
		//生成文字验证码
		String code = captcha.getCode();
		//5分钟后过期
		long expire = 60L * 5L;
		uuid = RedisKeys.CAPTCHA + uuid;
		redisService.set(uuid, code, expire);
		return captcha;
	}

	@Override
	public boolean validate(String uuid, String code) {
		uuid = RedisKeys.CAPTCHA + uuid;
		String value = redisService.get(uuid, String.class);
		if (value == null) {
			return false;
		}
		redisService.del(uuid);
		return value.equalsIgnoreCase(code);

	}
}
